package com.ningxun.rms.service.baserequire.impl;

import java.util.List;
import java.util.Objects;
import java.util.Date;

import com.ningxun.rms.common.annotation.DataScope;
import com.ningxun.rms.common.core.domain.entity.SysUser;
import com.ningxun.rms.common.core.domain.model.LoginUser;
import com.ningxun.rms.common.utils.DateUtils;
import com.ningxun.rms.common.utils.SecurityUtils;
import com.ningxun.rms.mapper.BusRequireApproveMapper;
import com.ningxun.rms.signup.domain.BusSignup;
import com.ningxun.rms.signup.mapper.BusSignupApproveMapper;
import com.ningxun.rms.signup.mapper.BusSignupMapper;
import com.ningxun.rms.utils.DataPermissionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ningxun.rms.mapper.BusRequireMapper;
import com.ningxun.rms.domain.busrequire.BusRequire;
import com.ningxun.rms.service.baserequire.IBusRequireService;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import com.ningxun.rms.system.service.ISysDeptService;

import static com.ningxun.rms.common.utils.PageUtils.startPage;

/**
 * 岗位需求发布Service业务层处理
 *
 * @author rms
 * @date 2025-07-15
 */
@Service
public class BusRequireServiceImpl implements IBusRequireService
{
    @Autowired
    private BusRequireMapper busRequireMapper;

    @Autowired
    private BusRequireApproveMapper busRequireApproveMapper;

    @Autowired
    private BusSignupMapper busSignupMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询岗位需求发布
     *
     * @param requireId 岗位需求发布主键
     * @return 岗位需求发布
     */
    @Override
    public BusRequire selectBusRequireByRequireId(Long requireId)
    {
        return busRequireMapper.selectBusRequireByRequireId(requireId);
    }

    /**
     * 查询岗位需求发布列表
     *
     * @param busRequire 岗位需求发布
     * @return 岗位需求发布
     */
    @Override
    public List<BusRequire> selectBusRequireList(BusRequire busRequire)
    {
        // 新增：支持地市筛选
        if (busRequire.getDeptId() != null) {
            java.util.List<Long> deptIds = sysDeptService.selectDeptIdsByParentId(busRequire.getDeptId());
            deptIds.add(busRequire.getDeptId()); // 包含自身
            busRequire.setDeptIds(deptIds);
        }
        startPage();
        return busRequireMapper.selectBusRequireList(busRequire);
    }
    @Override
    public List<BusRequire> selectBusRequireForExport(BusRequire busRequire)
    {
        // 新增：支持地市筛选
        if (busRequire.getDeptId() != null) {
            java.util.List<Long> deptIds = sysDeptService.selectDeptIdsByParentId(busRequire.getDeptId());
            deptIds.add(busRequire.getDeptId()); // 包含自身
            busRequire.setDeptIds(deptIds);
        }
        return busRequireMapper.selectBusRequireList(busRequire);
    }

    /**
     * 新增岗位需求发布
     *
     * @param busRequire 岗位需求发布
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBusRequire(@Validated BusRequire busRequire)
    {
        busRequire.setCreateTime(DateUtils.getNowDate());
        //部门权限相关
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = loginUser.getUser();
        busRequire.setDeptId(currentUser.getDeptId());

        //新增时设置审核状态为审核，失效状态为失效
        busRequire.setApproveState(1L);//0通过 1审核 2驳回
        busRequire.setRequireState(1L);//0正常 1过期 删除 非通过 岗位数量<1

        // 新增内容表
        int result = busRequireMapper.insertBusRequire(busRequire);

        //审核表新增 传id和状态
        busRequireApproveMapper.insertBusRequireApproveByRequireId(busRequire.getRequireId(),busRequire.getRequireState());

        return result;
    }

    /**
     * 修改岗位需求发布
     *
     * @param busRequire 岗位需求发布
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBusRequire( BusRequire busRequire)
    {

        //查询原有数据
        BusRequire old = busRequireMapper.selectBusRequireFieldsByRequireId(busRequire.getRequireId());
//        ObjectUtils.isEmpty()
        //检查是否更改原有数据
        boolean changed = false;
        if (!Objects.equals(old.getContent(),busRequire.getContent())) changed = true;
        if (!Objects.equals(old.getPost(),busRequire.getPost())) changed = true;
        if (!Objects.equals(old.getDemandType(),busRequire.getDemandType())) changed = true;
        if (!Objects.equals(old.getExpirationTime(),busRequire.getExpirationTime())) changed = true;
        if (!Objects.equals(old.getQuantity(),busRequire.getQuantity())) changed = true;
        if (!Objects.equals(old.getUnit(),busRequire.getUnit())) changed = true;
        if (!Objects.equals(old.getProject(),busRequire.getProject())) changed = true;
        if (!Objects.equals(old.getIntention(),busRequire.getIntention())) changed = true;
        if (!Objects.equals(old.getContact(),busRequire.getContact())) changed = true;
        if (!Objects.equals(old.getNumber(),busRequire.getNumber())) changed = true;
        if (!Objects.equals(old.getRemark(),busRequire.getRemark())) changed = true;

        if(changed){
            busRequire.setModifyTime(DateUtils.getNowDate());
            //修改本条信息状态
            busRequire.setApproveState(1L);//0通过 1审核 2驳回
            busRequire.setRequireState(1L);//0正常 1失效：过期 删除 非通过 岗位数量<1

            // 同步更新审核表状态
            int updated = busRequireApproveMapper.updateApproveStateByRequireId(busRequire.getRequireId(), 1L);
            if(updated == 0) {
                //审核记录不存在
                //创建审核记录
                busRequireApproveMapper.insertBusRequireApproveByRequireId(busRequire.getRequireId(), 1L);
            }
            busRequireApproveMapper.updateApproveStateByRequireId(busRequire.getRequireId(), 1L);
        }else {
            busRequire.setModifyTime(old.getModifyTime());
        }
        //校验部门权限
        BusRequire dbData = busRequireMapper.selectBusRequireByRequireId(busRequire.getRequireId());
        DataPermissionUtils.checkPermission(dbData); // 关键校验

        return busRequireMapper.updateBusRequire(busRequire);
    }

    /**
     * 批量删除岗位需求发布
     *
     * @param requireIds 需要删除的岗位需求发布主键
     * @return 结果
     */
    @Override
    public int deleteBusRequireByRequireIds(Long[] requireIds)
    {
        if(!busSignupMapper.selectBusSignupByRequireIds(requireIds).isEmpty()) {
            for (BusSignup busSignup : busSignupMapper.selectBusSignupByRequireIds(requireIds)) {
                if (busSignup.getApproveStatus() == 0 || busSignup.getApproveStatus() == 1) {
                    throw new RuntimeException("该岗位已有人报名成功或正在报名中");
                }
            }
        }
        return busRequireMapper.deleteBusRequireByRequireIds(requireIds);
    }

    /**
     * 删除岗位需求发布信息
     *
     * @param requireId 岗位需求发布主键
     * @return 结果
     */
    @Override
    public int deleteBusRequireByRequireId(Long requireId)
    {
        BusSignup busSignup = busSignupMapper.selectBusSignupByRequireId(requireId);
        if (busSignup != null) {
            if (busSignup.getApproveStatus() == 0 || busSignup.getApproveStatus() == 1) {
                throw new RuntimeException("该岗位已有人报名成功或正在报名中");
            }
        }
        return busRequireMapper.deleteBusRequireByRequireId(requireId);
    }

    //定时任务：查询所有生效的list，比较当前时间和过期时间，符合过期的改为失效
    @Override
    public void expireRequires() {
        List<BusRequire> list = busRequireMapper.selectUnexpiredRequires();
        Date now = new Date();
        for (BusRequire require : list) {
            if (require.getExpirationTime() != null && require.getExpirationTime().before(now)) {
                BusRequire update = new BusRequire();
                update.setRequireId(require.getRequireId());
                update.setRequireState(1L); // 1为失效
                busRequireMapper.updateBusRequire(update);
            }
        }
    }

    @Override
    public List<BusRequire> selectFrontBusRequireList(BusRequire busRequire) {
        return busRequireMapper.selectFrontBusRequireList(busRequire);
    }

    @Override
    public BusRequire selectFrontBusRequireByDeptId(Long deptId) {
        return busRequireMapper.selectFrontBusRequireByDeptId(deptId);
    }

    @Override
    public BusRequire selectFrontBusRequireByRequireId(Long requireId) {
        return busRequireMapper.selectBusRequireByRequireId(requireId);
    }

    @Override
    public List<BusRequire> selectInfo(String searchQuery,List<Long> deptId) {
        return busRequireMapper.selectInfo(searchQuery,deptId);
    }

}
